from subprocess import Popen
from subprocess import PIPE
from subprocess import STDOUT
from subprocess import call

import StringIO
import glob
import random
import os
import string
import time

#TODO: add an user name as an argument
def run(prog):
	direc,name = genFileName() 
	call(['mkdir', '-p', direc])

	pyName = direc + name + '.py'
	f = open(pyName, 'w')
	f.write(prog)
	f.close()

	cmd = ['python',pyName]
	proc = Popen(cmd, stderr=STDOUT, stdout=PIPE)
	retCode = 'OK'

	for _ in range(3):
		time.sleep(1)
		if proc.poll() is not None:
			break
		
	if proc.poll() is None:
		proc.kill()
		retCode = 'KILLED'

	fileList = glob.glob(direc + name + '.*')
	for f in fileList:
		os.remove(f)

	if retCode == 'OK':
		return retCode, proc.communicate()[0]
	return retCode, ''


def genFileName(size=32, chars=string.ascii_letters + string.digits):
	direc = 'tmp/'
	name = ''.join(random.choice(chars) for x in range(size))
	return direc, name
